package com.ruoyi.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.domain.*;
import com.ruoyi.mapper.*;
import com.ruoyi.utils.DateUtil;
import com.ruoyi.utils.OrderUtils;
import com.ruoyi.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import com.ruoyi.service.IAdvOrdersService;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-13
 */
@Slf4j
@Service
public class AdvOrdersServiceImpl implements IAdvOrdersService {
    @Autowired
    private AdvOrdersMapper advOrdersMapper;

    @Autowired
    private AdvOrdersdetailMapper advOrdersdetailMapper;

    @Autowired
    private AdvMembersaddrMapper advMembersaddrMapper;

    @Autowired
    private AdvMembersMapper advMembersMapper;

    @Autowired
    private AdvInoutstockMapper advInoutstockMapper;

    @Autowired
    private AdvProductsMapper advProductsMapper;

    @Autowired
    private WxAppServiceImpl wxAppService;


    /**
     * 查询
     *
     * @param advOrdersId 主键
     * @return
     */
    @Override
    public AdvOrders selectAdvOrdersByAdvOrdersId(Long advOrdersId) {
        return advOrdersMapper.selectAdvOrdersByAdvOrdersId(advOrdersId);
    }

    /**
     * 查询列表
     *
     * @param advOrders
     * @return
     */
    @Override
    public List<AdvOrders> selectAdvOrdersList(AdvOrders advOrders) {
        return advOrdersMapper.selectAdvOrdersList(advOrders);
    }

    /**
     * 新增
     *
     * @param advOrders
     * @return 结果
     */
    @Transactional // 确保事务一致
    @Override
    public int insertAdvOrders(AdvOrders advOrders) {
        // 先向订单表中添加数据, 防止外键约束
        Long orderAmount = advOrders.getOrdersNum() * advOrders.getProductPrice();
        advOrders.setOrdersamount(Double.valueOf(orderAmount));
        advOrders.setAdvOrdersdate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        advOrders.setOrderStatus(1L);
        advOrders.setOrdersno(OrderUtils.genOrdersNo("D"));
        advOrders.setBalFlag("0");
        Long advOrdersId = Long.valueOf(advOrdersMapper.insertAdvOrders(advOrders));

        // 然后向关联表中添加数据
        AdvOrdersdetail advOrdersdetail = new AdvOrdersdetail(
                UUIDUtils.timeMillisId(),
                advOrdersId,
                advOrders.getAdvProductsId(),
                advOrders.getOrdersNum()
        );
        advOrdersdetailMapper.insertAdvOrdersdetail(advOrdersdetail);

        return 1;
    }

    public int choseGive(Long advOrdersId,  Long advProductId) {
        AdvOrdersdetail advOrdersdetail = new AdvOrdersdetail(
                UUIDUtils.timeMillisId(),
                advOrdersId,
                advProductId,
                1L
        );
        int i = advOrdersdetailMapper.insertAdvOrdersdetail(advOrdersdetail);
        return i;
    }

    @Transactional // 确保事务一致
    @Override
    public int insertAdvOrdersApp(AdvOrders advOrders) {
        String start = advOrders.getProductType() == 1?"D":"C";
        System.out.println("订单的类型 =====> " + start);
        System.out.println("添加订单的参数 ===> " + advOrders);
        Long advOrdersId = null;
        AdvOrders unsettled = null;
        // 首先根据上传的信息判断当前用户是否存在未结算订单
        List<AdvOrders> unsettleds = advOrdersMapper.findUnsettled(advOrders.getAdvMembersId());
        // 表示是设备产品
        if (advOrders.getProductType() == 1) {
            for (AdvOrders order : unsettleds) {
                if (order.getOrdersno().startsWith("D")) { // 查询到未结算的产品订单
                    unsettled = order;
                }
            }
        }
        // 表示是内容产品
        if (advOrders.getProductType() == 2) {
            // 查询用户是否已经购买过这个产品, 如果已经购买过了, 就提示不能重复购买
            for (AdvOrders order : unsettleds) {
                if (order.getOrdersno().startsWith("C")) { // 查询到未结算的内容订单
                    unsettled = order;
                }
            }
        }
        if (unsettled != null) {
            // 如果未null, 表示当前存在未支付订单, 就不生成订单, 产品直接添加到这个订单下面
            advOrdersId = unsettled.getAdvOrdersId();

            // 判断当前订单是否已经包含所选的产品, 如果包含了且是设备产品就把数量相加， 如果是内容产品就直接返回
            List<AdvOrdersdetail> advOrdersdetails =
                    advOrdersdetailMapper.selectAdvOrdersdetailListApp(advOrdersId, advOrders.getAdvProductsId());
            if (advOrdersdetails.size() != 0 && advOrdersdetails != null) {
                if (advOrders.getProductType() == 1) {
                    // 把设备产品的数量相加
                    AdvOrdersdetail advOrdersdetail = advOrdersdetails.get(0);
                    advOrdersdetail.setOrdersNum(advOrdersdetail.getOrdersNum() + advOrders.getOrdersNum());
                    advOrdersdetailMapper.updateAdvOrdersdetail(advOrdersdetail);
                    System.out.println("数量更新完毕");
                    // 还要更新订单的总金额
                    AdvOrders orders = new AdvOrders();
                    Long orderAmount = advOrders.getOrdersNum() * advOrders.getProductPrice();
                    orders.setOrdersamount(advOrdersdetail.getOrdersamount() + Double.valueOf(orderAmount));
                    orders.setAdvOrdersId(unsettled.getAdvOrdersId());
                    advOrdersMapper.updateAdvOrders(orders);
                    System.out.println("更新金额完毕");
                    return 1;
                } else {
                    return 1;
                }
            } else {
                System.out.println(unsettled);
                System.out.println(advOrders);
                // 如果没有包含, 就要把新增的产品的金额添加到订单上
                unsettled.setOrdersamount(unsettled.getOrdersamount() + (advOrders.getOrdersNum() * advOrders.getProductPrice()));
                advOrdersMapper.updateAdvOrders(unsettled);
            }
        } else {
            // 反之则需要生成订单
            // 先向订单表中添加数据, 防止外键约束
            Long orderAmount = advOrders.getOrdersNum() * advOrders.getProductPrice();
            advOrders.setOrdersamount(Double.valueOf(orderAmount));
            advOrders.setAdvOrdersdate(DateUtil.getDate_YYYY_MM_dd_HH_mm_ss());
            advOrders.setOrderStatus(1L);
            advOrders.setOrdersno(OrderUtils.genOrdersNo(start));
            advOrders.setBalFlag("0");
            advOrders.setAdvMembersaddrId(
                    advOrdersdetailMapper.getDefaultAddressId(advOrders.getAdvMembersId()) + ""
            );
            advOrdersMapper.insertAdvOrders(advOrders);
            advOrdersId = advOrders.getAdvOrdersId();
        }
        // 然后向关联表中添加数据
        AdvOrdersdetail advOrdersdetail = new AdvOrdersdetail(
                UUIDUtils.timeMillisId(),
                advOrdersId,
                advOrders.getAdvProductsId(),
                advOrders.getOrdersNum()
        );
        advOrdersdetailMapper.insertAdvOrdersdetail(advOrdersdetail);

        return 1;
    }

    /**
     * 修改
     *
     * @param advOrders
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAdvOrders(AdvOrders advOrders) {
        // 修改订单状态的时候需要把赠送的订单也设置为已经付款
        AdvOrders unsettled = null;
        AdvOrders dUnsettled = null;
        // 首先根据上传的信息判断当前用户是否存在未结算订单
        List<AdvOrders> unsettleds = advOrdersMapper.findUnsettled(advOrders.getAdvMembersId());
        // 表示是设备产品
        for (AdvOrders order : unsettleds) {
            if (order.getOrdersno().startsWith("S")) {
                unsettled = order;
            }
            if (order.getOrdersno().startsWith("D")) {
                dUnsettled = order;
            }
        }
        if(unsettled != null && dUnsettled.getAdvOrdersId().equals(advOrders.getAdvOrdersId())) {
            // 如果有赠送订单就结算
            AdvOrders giveOrders = new AdvOrders();
            giveOrders.setAdvOrdersId(unsettled.getAdvOrdersId());
            giveOrders.setOrderStatus(2L);
            advOrdersMapper.updateAdvOrders(giveOrders);
        }
        return advOrdersMapper.updateAdvOrders(advOrders);
    }

    /**
     * 批量删除
     *
     * @param advOrdersIds 需要删除的主键
     * @return 结果
     */
    @Override
    public int deleteAdvOrdersByAdvOrdersIds(Long[] advOrdersIds) {
        try {
            return advOrdersMapper.deleteAdvOrdersByAdvOrdersIds(advOrdersIds);
        }catch (DataIntegrityViolationException e){
            log.error("订单删除失败{}",e);
            throw new RuntimeException("请先删除关联数据");
        }

    }

    /**
     * 删除信息
     *
     * @param advOrdersId 主键
     * @return 结果
     */
    @Override
    public int deleteAdvOrdersByAdvOrdersId(Long advOrdersId) {
        try {
            return advOrdersMapper.deleteAdvOrdersByAdvOrdersId(advOrdersId);
        }catch (DataIntegrityViolationException e){
            log.error("订单删除失败{}",e);
            throw new RuntimeException("请先删除关联数据");
        }
    }

    @Override
    public AdvOrders selectAdvOrdersByAdvMembersId(Long advMembersId, int productType) {
        AdvOrders unsettled = null;
        // 首先根据上传的信息判断当前用户是否存在未结算订单
        List<AdvOrders> unsettleds = advOrdersMapper.findUnsettled(advMembersId);
        if (productType == 1) {
            // 表示是设备产品
            for (AdvOrders order : unsettleds) {
                if (order.getOrdersno().startsWith("D")) {
                    unsettled = order;
                }
            }
        }
        if (productType == 2) {
            // 表示是内容产品
            for (AdvOrders order : unsettleds) {
                if (order.getOrdersno().startsWith("C")) {
                    unsettled = order;
                }
            }
        }
        return unsettled;
    }

    @Transactional
    @Override
    public AdvOrders getGive(Long advMembersId, int productType) {
        AdvOrders productOrders = null;
        AdvOrders unsettled = null;
        // 首先根据上传的信息判断当前用户是否存在未结算订单
        List<AdvOrders> unsettleds = advOrdersMapper.findUnsettled(advMembersId);
        // 表示是设备产品
        for (AdvOrders order : unsettleds) {
            if (order.getOrdersno().startsWith("S")) {
                unsettled = order;
            }
            if (order.getOrdersno().startsWith("D")) {
                productOrders = order;
            }
        }
        if(unsettled == null) {
            // 如果没有订单需要创建一个订单
            AdvOrders advOrders = new AdvOrders();
            Long orderAmount = 0L;
            advOrders.setOrdersamount(0.0);
            advOrders.setAdvOrdersdate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            advOrders.setOrderStatus(1L);
            advOrders.setOrdersno(OrderUtils.genOrdersNo("S"));
            advOrders.setAdvMembersId(advMembersId);
            advOrders.setBalFlag("0");
            if(productOrders != null) {
                System.out.println("未付款订单为空");
                // 把产品订单的编号设置进入赠送的订单中
                advOrders.setRefOrdersno(productOrders.getOrdersno());
            }
            Long advOrdersId = Long.valueOf(advOrdersMapper.insertAdvOrders(advOrders));
            unsettled = advOrders;
        }
        return unsettled;
    }

    /**
     * 发货操作
     *
     * @param advOrders
     */
    @Override
    public int updateBySendGoods(AdvOrders advOrders) {
        System.out.println("发货操作----->"+advOrders);
        /**
         * 小程序同步发货
         */
        AdvMembers advMembers = advMembersMapper.selectAdvMembersByAdvMembersId(advOrders.getAdvMembersId());
        Map<String, String> result = wxAppService.deliverGoods(advOrders.getOrdersno(), advMembers.getWeOpenid());
        return advOrdersMapper.updateBySendGoods(advOrders);
    }

    @Override
    public boolean selectOutInCount(Long advOrdersId) {
        int odnum = advOrdersdetailMapper.selectOrderCountById(advOrdersId);
        int oinum = advOrdersdetailMapper.selectOutInCountById(advOrdersId);
        System.out.println("出入库表----"+oinum+",订单表====>"+odnum);
        if (odnum == oinum) {
            return true;
        }
        return false;
    }

    /**
     * 根据订单id查询出库设备编号
     *
     * @param advOrdersdetail
     * @return
     */
    @Override
    public Map<String, Object> queryDeviceNoByProductId(AdvOrdersdetail advOrdersdetail) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<AdvInoutstock> allDeviceNo = advInoutstockMapper.queryAllDeviceNo(advOrdersdetail.getAdvProductsId(), advOrdersdetail.getAdvOrdersId());
        map.put("allDeviceNo", allDeviceNo);
        return map;
    }

    /**
     * 处理出库
     *
     * @param advInoutstock
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exeOutGoods(AdvInoutstock advInoutstock) {
        try {
            // 获取当前日期
            //先将此订单此产品的所有adv_inoutstock中相关订单的出库所有数据出库状态更改为1
            advInoutstockMapper.updateIsIn(advInoutstock.getAdvOrdersId(), advInoutstock.getAdvProductsId());
            advInoutstockMapper.updateIsOut(advInoutstock.getAdvOrdersId(), advInoutstock.getAdvProductsId(), advInoutstock.getListDevicesno(),advInoutstock.getOutstockDate() ,advInoutstock.getMemberAccount(),advInoutstock.getAdvMembersId());
            int stocknum = advProductsMapper.queryProductBefore(advInoutstock.getAdvProductsId());
            advProductsMapper.subStock(advInoutstock.getAdvProductsId(),stocknum,advInoutstock.getListDevicesno().size(),advInoutstock.getMyNum());
        } catch (Exception e) {
            log.error("处理出库失败{}",e);
            // 处理异常，如果需要可以做额外的操作
            throw e; // 确保异常抛出以触发事务回滚
        }
    }

    @Override
    public boolean isGet(String advOrdersId) {
        int nums = advOrdersMapper.isGet(advOrdersId);
        return nums != 0;
    }

    /**
     * 小程序不分页查询订单
     * @param advOrders
     * @return
     */
    @Override
    public List<AdvOrders> selectAllByAppOrderList(AdvOrders advOrders) {
        return advOrdersMapper.selectAllByAppOrderList(advOrders);
    }

    /**
     * 小程序申请退款
     */
    @Override
    public void exeRequestOrderRefund(AdvOrders advOrders) {
        String orderStatus = OrderUtils.chgStatus(advOrders.getOrderStatus() + "", "退款");
        advOrdersMapper.exeRequestOrderRefund(advOrders.getAdvOrdersId(),orderStatus);
    }

    @Override
    public void exeGoodsChange(AdvOrders advOrders) {
        if (advOrders.getRemark()==null){
             advOrders.setOrderStatus(3L);
            String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
             advOrders.setAdvSenddate(currentDate);
        }else {
            advOrders.setOrderStatus(8L);
        }
        advOrdersMapper.exeGoodsChange(advOrders);
    }

    /**
     * 小程序申请退换货
     * @param advOrders
     * @return
     */
    @Override
    public boolean goodsChangeRequest(AdvOrders advOrders) {
        advOrders.setOrderStatus(7L);
        advOrdersMapper.exeGoodsChange(advOrders);
        return true;
    }

    @Override
    public AdvOrders selectOrderPayByOrderId(Long advOrdersId) {
        return advOrdersMapper.selectOrderPayByOrderId(advOrdersId);
    }

    @Override
    public void updateOrdersNum(List<AdvOrders> advOrders) {
        for (AdvOrders advOrder : advOrders) {
            advOrdersdetailMapper.updateOrdersNum(advOrder);
        }
    }

    @Override
    public int cancelChoseGive(Long advOrdersId, Long advProductId) {
        int i = advOrdersdetailMapper.deleteByOrderIdAndProductId(advOrdersId, advProductId);
        return i;
    }

}
